package cn.zspt.fingerJoy.config;

import cn.zspt.fingerJoy.util.JwtUtils;
import cn.zspt.fingerJoy.util.MsgEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token= request.getHeader("Authorization");
        try{
            JwtUtils.verfy(token);
        }catch (Exception e){
            Map<String,Object> map=new HashMap<>();
            ObjectMapper objectMapper=new ObjectMapper();
            map.put("code", MsgEnum.NOT_AUTH.getCode());
            map.put("msg",MsgEnum.NOT_AUTH.getMsg());
            String data=objectMapper.writeValueAsString(map);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer=response.getWriter();
            writer.write(data);
            writer.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
